package com.chenjie.crud.handler;// ...
import com.chenjie.crud.enums.ResponseBase;
import com.chenjie.crud.enums.ResultCodeEnum;
import com.chenjie.crud.exception.CMSException;
import com.chenjie.crud.exception.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;

/**全局异常处理
 * @author chenjie
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**-------- 通用异常处理方法 --------**/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseBase error(Exception e) {
        // e.printStackTrace();
        log.error(ExceptionUtil.getMessage(e));
        return ResponseBase.error(); // 通用异常结果
    }

    /**-------- 指定异常处理方法 --------**/
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResponseBase error(NullPointerException e) {
        e.printStackTrace();
        return ResponseBase.setResult(ResultCodeEnum.NULL_POINT);
    }

    @ExceptionHandler(HttpClientErrorException.class)
    @ResponseBody
    public ResponseBase error(IndexOutOfBoundsException e) {
        e.printStackTrace();
        return ResponseBase.setResult(ResultCodeEnum.HTTP_CLIENT_ERROR);
    }

    /**-------- 自定义定异常处理方法 --------**/
    @ExceptionHandler(CMSException.class)
    @ResponseBody
    public ResponseBase error(CMSException e) {
        e.printStackTrace();
        ResponseBase error = ResponseBase.error();
        error.setCode(e.getCode());
        error.setMessage(e.getMessage());
        return error;
    }
}
